#coding:utf-8
# 处理依赖数据
import sys
import json
sys.path.append('F:/A_RuanJian/Py_project/imooc/')
from util.operation_excel import OperationExcel
from data.runmethod import RunMethod
from data.get_data import GetData
from jsonpath_rw import parse
from util.operation_json import OperetionJson,Path


class DependdentData:
	def __init__(self,case_id):
		self.case_id = case_id
		self.data = GetData()
		self.opera_excel = OperationExcel()

	# 通过case_id去获取该case_id的整行数据
	def get_case_line_data(self):
		rows_data = self.opera_excel.get_rows_data(self.case_id)
		return rows_data

	# 执行依赖测试，并判断是否需要添加cookie，然后获取结果
	def run_dependent(self):
		run_method = RunMethod()
		row_num  = self.opera_excel.get_row_num(self.case_id)

		request_data = self.data.get_data_for_json(row_num)
		cookie = self.data.is_cookie(row_num)
		method = self.data.get_request_method(row_num)
		url = self.data.get_request_url(row_num)
		header = self.data.get_header_for_json(row_num)
		header_type = self.data.get_header_type(row_num)

		if header_type == 'not_json':
			request_data = json.dumps(request_data)
		else:
			pass

		if cookie == 'yes':
			op_json = OperetionJson(Path.path_cookie)
			cookie= op_json.get_data('__outh')
			cookies = {
				'__outh':cookie
			}
			res = run_method.run_main(method,url,request_data,cookies,header)
		else:
			res = run_method.run_main(method,url,request_data,header)
		print res
		return json.loads(res)

	# 根据依赖的key去获取,并执行依赖测试case的响应,然后返回
	def get_data_for_key(self,row):
		depend_data = self.data.get_depend_key(row)
		response_data = self.run_dependent()
		try:
			male = parse(depend_data).find(response_data)
			a01 = [match.value for match in male][0]
		except:
			print (json.dumps(response_data, ensure_ascii=False))
			print ('错误：依赖数据获取失败')
		else:
			# print (a01)
			return a01




